package sim.ring.technical.comms;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.log4j.*;

import sim.ring.technical.comms.SerialReader;

public class SerialConnection {
	
	private Logger log = Logger.getLogger("sim.ring.technical.comms");
	
	public SerialConnection() {
		log.setLevel(Level.DEBUG);
	}
	
	public void connect(String portName, EventListenerInterface listener) throws Exception {
		CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
		if (portIdentifier.isCurrentlyOwned()) {
			log.error("Port " + portName + " is currently in use!");
			//TODO: throw exception
		} else {
			CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
			
			if (commPort instanceof SerialPort) {
				SerialPort serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
				
				InputStream in = serialPort.getInputStream();   
				(new Thread(new SerialReader(in, listener))).start();
			} else {
				log.error("Port " + portName + " is not a valid serial port!");
				//TODO: throw exception
			}
		}     
	}
}
